package com.cmcc.groupcontacts.firewall.activity;

import java.util.ArrayList;

import android.app.AlertDialog.Builder;
import android.app.NotificationManager;
import android.content.Context;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Message;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Toast;

import com.cmcc.groupcontacts.MainApp;
import com.cmcc.groupcontacts.MainApp.AfterBlockedCallbackEvent;
import com.cmcc.groupcontacts.common.SmsReceiver;
import com.cmcc.groupcontacts.firewall.activity.strategy.ActivityTitleStrategy;
import com.cmcc.groupcontacts.firewall.adapter.SmsListAdapter;
import com.cmcc.groupcontacts.firewall.business.FilterListBusiness;
import com.cmcc.groupcontacts.firewall.business.SmsListBusiness;
import com.cmcc.groupcontacts.firewall.dao.model.CallInfoVO;
import com.cmcc.groupcontacts.firewall.dao.model.SmsListVO;
import com.cmcc.groupcontacts.util.ExceptionHandler;
import com.cmcc.groupcontacts.util.IntentManager;
import com.cmcc.groupcontacts.util.StringUtil;
import com.cmcc.groupcontacts.util.ValidationUtil;
import com.yinhai.activity.R;

/**
 * 信息拦截记录Activity
 * 
 * @author 
 * 
 */
public class SmsListActivity extends BaseListActivity {
	private SmsListBusiness smsListBiz;

	private SmsListVO clickedSms;

	@Override
	public void setTitleStrategy() {
		titleStrategy = new ActivityTitleStrategy(this);
	}

	@Override
	public void setTitleButtons() {
		// 左边的“返回”按钮
		getLeftLayout().addView(createBackButton());
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.sms_list_activity);

		init();
		load();
	}

	private void init() {
		// 添加通话记录观察者的回调事件
		MainApp.getSmsCallbackEvents().add(new AfterBlockedCallbackEvent() {
			@Override
			public void invoke(Message msg) {
				load();
			}
		});
		// 其他初始化设置
		registerForContextMenu(getListView());
		setEmptyText("");
		getListView().setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
			@Override
			public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
				clickedSms = (SmsListVO) parent.getItemAtPosition(position);
				getListView().showContextMenu();
				return true;
			}
		});
	}

	private void load() {
		// 异步加载信息拦截记录
		new SmsListLoadTask().execute((Void[]) null);
	}

	@Override
	protected void onResume() {
		super.onResume();

		clearSmsNofitication();
	}

	/*
	 * 清除信息拦截系统通知
	 */
	private void clearSmsNofitication() {
		NotificationManager notificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
		for (Integer notificationId : SmsReceiver.notificationIdList) {
			notificationManager.cancel(notificationId);
		}
		SmsReceiver.notificationIdList.clear();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// TODO: 清空操作
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
		if (!ValidationUtil.isNullOrEmpty(clickedSms.getName())) {
			menu.setHeaderTitle(StringUtil.format("{0}({1})", clickedSms.getName(), clickedSms.getNumber()));
		} else {
			menu.setHeaderTitle(clickedSms.getNumber());
		}
		menu.add(0, 1, Menu.NONE, "删除");
		menu.add(0, 2, Menu.NONE, "呼叫号码");
		menu.add(0, 3, Menu.NONE, "短信回复");
		menu.add(0, 4, Menu.NONE, "保存为联系人");
		menu.add(0, 5, Menu.NONE, "加入白名单");
		menu.add(0, 6, Menu.NONE, "加入黑名单");
		menu.add(0, 7, Menu.NONE, "恢复到系统信息");
	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case 1:
			Builder builder = new Builder(this);
			builder.setTitle(R.string.hint);
			builder.setMessage("确定要删除这条信息拦截记录吗？");
			builder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					dialog.dismiss();

					boolean isSuccessful = false;
					try {
						isSuccessful = (smsListBiz.delete(clickedSms.getId()) > 0);
					} catch (Exception e) {
						ExceptionHandler.handle(e, "删除信息拦截记录时出错");
					}
					if (isSuccessful) {
						getBaseAdapter().getDataSource().remove(clickedSms);
						if (!getBaseAdapter().getDataSource().isEmpty()) {
							getBaseAdapter().notifyDataSetChanged();
						} else {
							setListAdapter(null);
						}
						Toast.makeText(SmsListActivity.this, R.string.delete_ok, Toast.LENGTH_SHORT).show();
					} else {
						Toast.makeText(SmsListActivity.this, R.string.delete_fail, Toast.LENGTH_SHORT).show();
					}
				}
			});
			builder.setNegativeButton(R.string.cancel, null);
			builder.show();
			break;
		case 2:
			IntentManager.call(this, clickedSms.getNumber());
			break;
		case 3:
			IntentManager.sms(this, clickedSms.getNumber(), "");
			break;
		case 4:
			IntentManager.addToContacter(this, clickedSms.getNumber());
			break;
		case 5:
			addToFilterList(false);
			break;
		case 6:
			addToFilterList(true);
			break;
		case 7:
			// TODO: 恢复到系统信息
		}
		return super.onContextItemSelected(item);
	}

	private void addToFilterList(boolean isBlackList) {
		CallInfoVO callInfo = new CallInfoVO();
		callInfo.setNumber(clickedSms.getNumber());
		callInfo.setName(clickedSms.getName());
		if (new FilterListBusiness().insert(callInfo, isBlackList) >= 0) {
			Toast.makeText(SmsListActivity.this, R.string.insert_ok, Toast.LENGTH_SHORT).show();
		} else {
			Toast.makeText(SmsListActivity.this, R.string.insert_fail, Toast.LENGTH_SHORT).show();
		}
	}

	/*
	 * 异步加载信息拦截记录
	 */
	private class SmsListLoadTask extends AsyncTask<Void, Integer, ArrayList<SmsListVO>> {
		@Override
		protected ArrayList<SmsListVO> doInBackground(Void... params) {
			smsListBiz = new SmsListBusiness();
			return smsListBiz.getSmsList();
		}

		@Override
		protected void onPostExecute(ArrayList<SmsListVO> smsList) {
			if (!ValidationUtil.isNullOrEmpty(smsList)) {
				setListAdapter(new SmsListAdapter(SmsListActivity.this, smsList));
			} else {
				setListAdapter(null);
			}
		}
	}
}
